
#import "HelpViewController.h"
#import "Util.h"
#import <QuartzCore/QuartzCore.h>

@interface HelpViewController()


- (void)reloadPages;
- (void)loadPage:(NSInteger)page;
- (void)loadAdjacencyPages:(NSNumber *)page;
- (void)scrollToPage:(NSInteger)page animated:(BOOL)animated;

- (void)refreshPage;

- (void)clearPageViews;

- (IBAction)doneAction:(id)sender;

- (void)finishHelp;


@property (nonatomic, retain) NSMutableArray * pageViews;
@property (nonatomic, assign) BOOL bPageRefreshed;

@end


@implementation HelpViewController

@synthesize pageScrollView = _pageScrollView;
@synthesize pageCtrl = _pageCtrl;
@synthesize bAppearAnimated = _bAppearAnimated;

@synthesize pageViews;
@synthesize bPageRefreshed;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization.
//    }
//    return self;
//}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.title = @"帮助";
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"跳过" 
																			   style:UIBarButtonItemStylePlain 
																			  target:self 
																			  action:@selector(doneAction:)] autorelease];
	
	self.pageScrollView.showsHorizontalScrollIndicator = NO;
    self.pageScrollView.showsVerticalScrollIndicator = NO;
	
	//[self reloadPages];
}


- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	self.bPageRefreshed = YES;
	
	if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:)])
	{
		[self.navigationController.navigationBar performSelector:@selector(setBackgroundImage:) withObject:[UIImage imageNamed:@"nav_bar_sub.png"]];
	}
	
	CGSize scrollSize = self.pageScrollView.contentSize;
	scrollSize.height = self.pageScrollView.frame.size.height;
	self.pageScrollView.contentSize = scrollSize;
	
	[self reloadPages];
	
	if (_bAppearAnimated) 
	{
		CATransition *transition = [CATransition animation];
		//transition.duration = 1.0;
		transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];/* 动画的开始与结束的快慢*/
		transition.type = @"moveIn"; /* 各种动画效果*/
		//@"cube" @"moveIn" @"reveal" @"fade"(default) @"pageCurl" @"pageUnCurl" @"suckEffect" @"rippleEffect" @"oglFlip"
		UIInterfaceOrientation orientation = self.interfaceOrientation;
		if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
		{		
			transition.subtype = (UIInterfaceOrientationLandscapeLeft == orientation) ? kCATransitionFromTop : kCATransitionFromBottom;  /* 动画方向*/	
		}	
		else	
		{		
			transition.subtype = (UIInterfaceOrientationPortrait == orientation) ? kCATransitionFromLeft : kCATransitionFromRight;   /* 动画方向*/	
		}
		[[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:nil];
	}

	
}

- (void)viewDidDisappear:(BOOL)animated
{
	if (_hvDelegate && [_hvDelegate performSelector:@selector(HelpViewFinish)]) {
		[_hvDelegate performSelector:@selector(HelpViewFinish)];
	}
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
	
	_hvDelegate = nil;
	
	[self clearPageViews];
	
	self.pageScrollView = nil;
	self.pageCtrl = nil;
	
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	
	_hvDelegate = nil;
	
	[self clearPageViews];
	[_pageScrollView release];
    [_pageCtrl release];
	
    [super dealloc];
}

- (id)initWithDelegate:(id<HelpViewDelegate>)hvDelegate
{
	self = [super initWithNibName:@"HelpViewController" 
						   bundle:nil];
	
	if (self) {
		_hvDelegate = hvDelegate;
	}
	
	return self;
}

- (void)setNewPageViews:(NSArray *)newPageViews
{
	[self clearPageViews];
	self.pageViews = [NSMutableArray arrayWithArray:newPageViews];
	
	[self reloadPages];
}

- (IBAction)changePage:(id)sender
{
    NSInteger page = self.pageCtrl.currentPage;
	
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
	[self loadAdjacencyPages:[NSNumber numberWithInteger:page]];
    
	// update the scroll view to the appropriate page
	[self scrollToPage:page animated:YES];
    
	// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
    //pageControlUsed = YES;
}

- (void)reloadPages
{
	if (self.pageScrollView && self.pageCtrl) 
	{
		CGRect scrollFrame = self.pageScrollView.frame;
		NSInteger numOfPages = [self.pageViews count];
		
		self.pageScrollView.contentSize = CGSizeMake(scrollFrame.size.width * numOfPages, scrollFrame.size.height);
		
		self.pageCtrl.numberOfPages = numOfPages;
		self.pageCtrl.currentPage = 0;
		
		[self loadPage:0];
		[self loadPage:1];
		
		[self scrollToPage:0 animated:NO];
	}

}

- (void)loadPage:(NSInteger)page
{
	if (page < 0 || page >= self.pageCtrl.numberOfPages)
	{
        return;
	}
    
	id pageObj = [self.pageViews objectAtIndex:page];
    UIView * pageView = [pageObj isKindOfClass:[UIView class]] ? pageObj : nil;
    if (pageView && pageView.superview == nil)
    {
        CGRect frame = self.pageScrollView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
        pageView.frame = frame;
		//pageView.autoresizingMask = AutoresizingMaskFull;
		pageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | 
								UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        [self.pageScrollView addSubview:pageView];
    }
	
}

- (void)loadAdjacencyPages:(NSNumber *)page
{
	[self loadPage:[page integerValue] - 1];
	[self loadPage:[page integerValue] + 1];
}

- (void)scrollToPage:(NSInteger)page animated:(BOOL)animated;
{
	id pageObj = [self.pageViews objectAtIndex:page];
    UIView * pageView = [pageObj isKindOfClass:[UIView class]] ? pageObj : nil;
    [self.pageScrollView scrollRectToVisible:pageView.frame animated:animated];
}

- (void)refreshPage
{
	if (self.bPageRefreshed == NO) {
		CGFloat pageWidth = self.pageScrollView.frame.size.width;
		NSInteger page = floor((self.pageScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
		
		if (self.pageCtrl.currentPage != page) {
			self.bPageRefreshed = YES;
			self.pageCtrl.currentPage = page;
			// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
			[self performSelectorOnMainThread:@selector(loadAdjacencyPages:) 
								   withObject:[NSNumber numberWithInteger:page] 
								waitUntilDone:NO];
		}

	}
}

- (void)clearPageViews
{
	for (UIView * pageView in self.pageViews) {
		[pageView removeFromSuperview];
	}
	[self.pageViews removeAllObjects];
	self.pageViews = nil;
}

- (IBAction)doneAction:(id)sender
{
	[self finishHelp];
}

- (void)finishHelp
{
	[self dismissModalViewControllerAnimated:NO];
	
	CATransition *transition = [CATransition animation];
	//transition.duration = 1.0;
	transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];/* 动画的开始与结束的快慢*/
	transition.type = @"moveIn"; /* 各种动画效果*/
	//@"cube" @"moveIn" @"reveal" @"fade"(default) @"pageCurl" @"pageUnCurl" @"suckEffect" @"rippleEffect" @"oglFlip"
	UIInterfaceOrientation orientation = self.interfaceOrientation;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
	{		
		transition.subtype = (UIInterfaceOrientationLandscapeLeft == orientation) ? kCATransitionFromBottom : kCATransitionFromTop;  /* 动画方向*/	
	}	
	else	
	{		
		transition.subtype = (UIInterfaceOrientationPortrait == orientation) ? kCATransitionFromRight : kCATransitionFromLeft;   /* 动画方向*/	
	}
	[[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:nil];
	
//	if (_hvDelegate && [_hvDelegate performSelector:@selector(HelpViewFinish)]) {
//		[_hvDelegate performSelector:@selector(HelpViewFinish)];
//	}
}

#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
	if (self.pageScrollView.decelerating) 
	{
		[self refreshPage];
	}
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
	if(self.pageCtrl.currentPage + 1 == self.pageCtrl.numberOfPages && 
	   (self.pageScrollView.contentSize.width < self.pageScrollView.contentOffset.x + self.pageScrollView.frame.size.width)) 
	{
		//[self dismissModalViewControllerAnimated:YES];
		[self finishHelp];
		return;
	}
	self.bPageRefreshed = NO;
}

 // At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //pageControlUsed = NO;
}

 // At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

	//NSLog(@"scrollViewDidEndDecelerating , current page: %d", self.pageCtrl.currentPage);
	
	self.bPageRefreshed = YES;
}

@end
